<?php 

namespace Home\Controller;
use Think\Controller;


class PublishController extends CommonController
{
	
	public function index(){
		if(I('get.')){
			$qid = I('get.qid');
			if(isset($_SESSION['uid'])){
				$sql = "select t1.qid,t1.title,t1.content,t1.kiss,t2.cname from question t1 left join category t2 on t1.cid=t2.cid where qid='$qid'";
				$quest = current(M()->query($sql));
				$this->assign('quest',$quest);
			}
		}
		$question = D('vercode')->getOne();

		$this->assign('question',$question);

		$category=M('category')->select();

		$newcate=array();

		foreach ($category as $v) {
			if($v['fid']==0){
				$newcate[]=$v;
			}
		}
		foreach ($newcate as $k => $v) {
			foreach ($category as $key => $value) {
				if($value['fid']==$v['cid']){
					$newcate[$k]['son'][]=$value;
				}
			}
		}
		$this->assign('newcate',$newcate);
		$this->assign('title','发表新帖');
		$this->display();
	}

	public function checkdata(){
		$data = I('post.');
		$answer = $data['vercode'];
		$res = D('vercode')->checkCode($answer);
		if(!$res){
			$this->ajaxReturn(["error"=>4,"info"=>'人类验证错误']);
		}
		$data['kiss'] = $data['experience'];
		$data['uid'] = $_SESSION['uid'];
		$data['create_time'] = time();

		$art = D('user');
		if(!$art->create($data,6)){
			$this->ajaxReturn(["error"=>2,"info"=>$art->getError()]);
		}
		$qid = $data['qid'];
		if($qid!=''){
			//var_dump($qid);exit;
			$result = M('question')->where(array('qid'=>$qid))->setField($data);

			if($result){
				$this->ajaxReturn(['error'=>0,'info'=>'编辑成功','url'=>U("home/discuss/index")."?qid=".$qid]);
			}
		}else{
			$qid = M('question')->add($data);
			$this->ajaxReturn(['error'=>0,'info'=>'发布成功','url'=>U("home/discuss/index")."?qid=".$qid]);
		}
	}
	public function upload(){
		//var_dump($_FILES);
		$upload = new \Think\Upload();// 实例化上传类
	    $upload->maxSize   =     3145728 ;// 设置附件上传大小
	    $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
	    $upload->rootPath  =     './Uploads/pic/'; // 设置附件上传根目录
	    $upload->savePath  =     ''; // 设置附件上传（子）目录
	    // 上传文件 
	    $info   =   $upload->upload();
	    if(!$info) {// 上传错误提示错误信息
	        //$this->error($upload->getError());
	        echo "失败";
	    }else{// 上传成功
	        $pic = __ROOT__.'/Uploads/pic/'.$info['file']['savepath'].$info['file']['savename'];

	        $arr=array(
	        	"code"=> 0,
	        	"msg"=> '成功',
	        	'data'=>array(
	        		'src'=>$pic,
	        		'title'=>'图片'
	        	)
	        );

	        echo json_encode($arr);
	    }
	}
}

 ?>